const express = require("express");
const app = express();
app.listen(3000, function () {
  console.log("3000端口开启了，可以访问: http://localhost:3000");
});
const path = require("path");
const fs = require("fs");
app.use("/static", express.static("staticPage/static"));
app.use(express.urlencoded({ extended: false }));
const serveFavicon = require("serve-favicon");
app.use(serveFavicon("favicon.ico"));
app.use(function (req, res, next) {
  let d = new Date();
  let year = d.getFullYear();
  let month = d.getMonth() + 1;
  let day = d.getDate();
  let h = d.getHours();
  let m = d.getMinutes();
  let s = d.getSeconds();
  req.time = ` ${year}年${month}月${day}日 ${h}：${m}：${s}`;
  next();
});
app.get('/',(req,res)=>{
  res.send('这是首页')
})
app.get("/login", (req, res) => {
  let filepath = path.join(__dirname, "/staticPage/login.html");
  res.sendFile(filepath);
});
app.get("/register", (req, res) => {
  let filepath = path.join(__dirname, "/staticPage/register.html");
  res.sendFile(filepath);
});
app.post("/login", (req, res) => {
  let a = null;
  if (fs.readFileSync("persons.json", "utf8")) {
    let result = JSON.parse(fs.readFileSync("persons.json", "utf8"));
    a = result.find((item) => req.body.tel == item.tel);
  } else {
    a = req.body;
  }
  if (a&&a.tel) {
    res.send("登录成功");
  } else {
    res.send("登录失败");
  }
});
app.post("/register", (req, res) => {
  let a = null;
  let result=[]
  if (fs.readFileSync("persons.json", "utf8")) {
    result = JSON.parse(fs.readFileSync("persons.json", "utf8"));
    a = result.find((item) => req.body.tel == item.tel);
  } else {
    a = req.body.tel?undefined:req.body;
  }
  if (a) {
    res.send("该账号已注册");
  } else if (!req.body.tel.replace(/^\s+|\s+$/, "")) {
    res.send("请输入用户名");
  } else if (!req.body.pass.replace(/^\s+|\s+$/, "")) {
    res.send("请输入密码");
  } else if (
    req.body.pass.replace(/^\s+|\s+$/, "") !=
    req.body.pass2.replace(/^\s+|\s+$/, "")
  ) {
    res.send("请输入密码");
  } else {
    let tel = req.body.tel;
    let pass = req.body.pass;
    let time = req.time;

    result.push({ tel, pass, time });
    fs.writeFileSync("persons.json", JSON.stringify(result), { flag: "w" });
    res.send("注册成功");
  }
});
